<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="60%">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="bindClassQueryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="班级名称" prop="classesName">
          <el-input
            v-model="queryParams.classesName"
            placeholder="请输入班级名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="班级编码" prop="classesCode">
          <el-input
            v-model="queryParams.classesCode"
            placeholder="请输入班级编码"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="学校" prop="schoolId">
          <el-input
            v-model="queryParams.schoolName"
            placeholder="请输入学校"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
            disabled
          />
        </el-form-item>
        <el-form-item label="机构名称" prop="collegeId">
          <el-select
            v-model.trim="queryParams.collegeId"
            clearable
            filterable
            placeholder="请选择机构"
            @keyup.enter="handleQuery"
            @change="changeCollege"
          >
            <el-option
              v-for="item in collegeList"
              :key="item.id"
              :label="item.collegeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业名称" prop="majorId">
          <el-select
            v-model.trim="queryParams.majorId"
            clearable
            filterable
            placeholder="请选择专业"
            @keyup.enter="handleQuery"
          >
            <el-option
              v-for="item in majorList"
              :key="item.id"
              :label="item.majorName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select
            v-model="queryParams.grade"
            placeholder="请选择状态"
            clearable
            class="!w-240px"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.CMIS_GRADE_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table
        v-loading="loading"
        :data="list"
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <!-- <el-table-column label="id" prop="id" /> -->
        <el-table-column type="selection" width="55" reserve-selection />
        <el-table-column label="班级名称" prop="classesName" show-overflow-tooltip />
        <el-table-column label="班级编码" prop="classesCode" show-overflow-tooltip />
        <el-table-column label="年级" prop="grade">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.CMIS_GRADE_TYPE" :value="scope.row.grade" />
          </template>
        </el-table-column>
        <el-table-column label="专业名称" prop="majorName" show-overflow-tooltip />
        <el-table-column label="机构名称" prop="collegeName" show-overflow-tooltip />
        <el-table-column label="学校名称" prop="schoolName" show-overflow-tooltip />
        <el-table-column
          label="创建时间"
          prop="createTime"
          :formatter="dateFormatter"
          show-overflow-tooltip
          width="180"
        />
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="submitEnable">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ClassesVO } from '@/api/cmis/classes'

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('绑定班级') // 弹窗的标题
import * as ClassesApi from '@/api/cmis/classes'
import * as CollegeApi from '@/api/cmis/college'
import * as MajorApi from '@/api/cmis/major'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import * as TeacherClassApi from '@/api/cmis/teacherClass'

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  createTime: [],
  classesName: null,
  classesCode: null,
  schoolId: null,
  schoolName: null,
  collegeId: null,
  majorId: null,
  grade: null
})
const formData = ref({
  teacherId: undefined,
  classesIds: []
})
const bindClassQueryFormRef = ref() // 搜索的表单

const collegeList = ref([]) //机构列表
const majorList = ref([]) //专业列表
const submitEnable = ref(true) // 是否允许提交
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const getCollegeList = async (schoolId: string) => {
  const res = await CollegeApi.getCollegeList({ schoolId })
  collegeList.value = res
}

// 获取专业列表
const getMajorList = async () => {
  const res = await MajorApi.getMajorList({
    schoolId: queryParams.schoolId,
    collegeId: queryParams.collegeId
  })
  majorList.value = res
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ClassesApi.getClassesPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  bindClassQueryFormRef.value.resetFields()
  handleQuery()
}

/** 打开弹窗 */
const open = async (teacherState: Array<any>) => {
  dialogVisible.value = true
  console.log('dialog.teacherState', teacherState)
  formData.value.teacherId = teacherState[0]
  queryParams.schoolId = teacherState[1]
  queryParams.schoolName = teacherState[2]

  // 获取机构列表
  queryParams.collegeId = null
  queryParams.majorId = null

  getCollegeList(teacherState[1])
  getMajorList()
  getList()
}

// 选择机构
const changeCollege = async () => {
  queryParams.majorId = null
  // 加载专业列表
  getMajorList()
}

const selectedClasses = ref<ClassesVO[]>([])
const handleSelectionChange = (val: ClassesVO[]) => {
  selectedClasses.value = val
  submitEnable.value = val.length <= 0
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  formData.value.classesIds = selectedClasses.value.map((item) => item.id)

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TeacherClassApi.BindTeacherClassVO
    await TeacherClassApi.bindTeacherClass(data)
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>
